0337. 打家劫舍 III【中等】
1. 📝 题目描述
小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为 root。
除了 root 之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果 两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
给定二叉树的 root。返回 在不触动警报的情况下,小偷能够盗取的最高金额。
示例 1:

txt
输入: root = [3,2,3,null,3,null,1]
输出: 7
解释: 小偷一晚能够盗取的最高金额 3 + 3 + 1 = 71
2
3
2
3
示例 2:

txt
输入: root = [3,4,5,1,3,null,1]
输出: 9
解释: 小偷一晚能够盗取的最高金额 4 + 5 = 91
2
3
2
3
提示:
- 树的节点数在
[1, 10^4]范围内 0 <= Node.val <= 10^4
2. 🎯 s.1 - 树形 DP
c
int* dfs(struct TreeNode* node) {
int* res = (int*)calloc(2, sizeof(int));
if (!node) return res;
int* left = dfs(node->left);
int* right = dfs(node->right);
int maxL = left[0] > left[1] ? left[0] : left[1];
int maxR = right[0] > right[1] ? right[0] : right[1];
res[0] = maxL + maxR;
res[1] = node->val + left[0] + right[0];
free(left); free(right);
return res;
}
int rob(struct TreeNode* root) {
int* res = dfs(root);
int ans = res[0] > res[1] ? res[0] : res[1];
free(res);
return ans;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
js
/**
* @param {TreeNode} root
* @return {number}
*/
var rob = function (root) {
function dfs(node) {
if (!node) return [0, 0] // [不抢, 抢]
const left = dfs(node.left)
const right = dfs(node.right)
const notRob = Math.max(left[0], left[1]) + Math.max(right[0], right[1])
const doRob = node.val + left[0] + right[0]
return [notRob, doRob]
}
const res = dfs(root)
return Math.max(res[0], res[1])
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
py
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if not node:
return 0, 0 # (不抢, 抢)
l_not, l_do = dfs(node.left)
r_not, r_do = dfs(node.right)
not_rob = max(l_not, l_do) + max(r_not, r_do)
do_rob = node.val + l_not + r_not
return not_rob, do_rob
return max(dfs(root))1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
- 时间复杂度:
,其中 是节点数 - 空间复杂度:
,递归栈深度
算法思路:
- 每个节点返回两个值:不抢该节点的最大收益和抢该节点的最大收益
- 不抢当前节点:子节点可抢可不抢;抢当前节点:子节点不能抢